import { getWebSocketUrl } from "/@/api/core/ws";

/**
 * 处理 web socket 返回的信息
 */
export const handlerMessage = (message: string) => {
    var data = JSON.parse(message);
    return data;
}

/**
 * web socket回调配置
 */
export type WebSocketCallBackConfig = {
    onOpen?: Function,
    onMessage?: Function
    onClose?: Function
}

/**
 * 生成一个 web socket实例
 */
export const newWebSocketInstance = (scoketId: string, config: WebSocketCallBackConfig): WebSocket => {
    const wsInstance = new WebSocket(getWebSocketUrl(scoketId));
    wsInstance.onopen = () => {
        console.log("ws连接成功....", scoketId);
        if (config?.onOpen) config.onOpen();
    }
    wsInstance.onmessage = (ev: MessageEvent<any>) => {
        if (config?.onMessage) config.onMessage(handlerMessage(ev.data))
    }
    wsInstance.onclose = () => {
        console.log("ws连接关闭....", scoketId);
        if (config?.onClose) config.onClose();
    }
    return wsInstance;
}